<template>
  <view class="venue-container">
    <scroll-view 
      class="venue-list" 
      :class="{ 'venue-list-expanded': isVenueListExpanded }"
      scroll-y
      ref="venueScrollView"
    >
      <view 
        v-for="(venueGroup, groupIndex) in groupedVenues" 
        :key="groupIndex" 
        class="recommended-venue"

      >
        <view class="venue-header">
          <view @click="toggleVenueDetails(groupIndex)" class="venue-logo">
            {{ venueGroup.logo }}
          </view>
          <view class="venue-info">
            <view @click="toggleVenueDetails(groupIndex)" class="venue-name">
              <view>
                {{ venueGroup.name }}
              </view>
            <view class="section-title-right" @click="toggleVenueDetails(groupIndex)">
              <text class="section-more-text">详情</text>
              <image class="section-more-arrow" src="../static/home/right.png" mode="widthFix" />
            </view>
            </view>
            <view @click="toggleVenueDetails(groupIndex)" class="venue-address">{{ venueGroup.address }}</view>
            <view @click="goToBooking(court.venue)" v-for="(court, courtIndex) in venueGroup.courts" 
                :key="courtIndex" class="venue-details">
              <view 
                
                class="court-item"
              >
                <view class="court-name">
                  
                  {{ court.name }}
                <text class="court-type" style="margin-left: 20rpx;">{{ court.courtType }}</text></view>
                <!-- <view class="court-info-row">
                  <text class="info-label">空闲时间</text>
                  <view class="time-slots">
                    <view 
                      v-for="(timeSlot, timeIndex) in court.availableTimeSlots" 
                      :key="timeIndex"
                      class="time-slot"
                    >
                      {{ timeSlot }}
                    </view>
                    <view v-if="court.availableTimeSlots.length === 0" class="no-time-slots">
                      暂无空闲时间
                    </view>
                  </view>
                </view> -->
                <view class="court-info-row">
                  <text class="info-label">场地价格</text>
                  <text class="court-type-1">{{ getPrice(court.venue.timeSlots) }}</text>
                </view>
              </view>
              <view class="venue-actions">
                <!-- <view class="venue-location" @click="openNavigation(court.venue)">
                  <image class="location-icon" src="../static/home/导航.png" mode="widthFix" />
                  <text class="distance-text">{{ court.distance }}km</text>
                </view> -->
                <view class="book-button-white" @click="openNavigation(court.venue)">
                  <!-- <image class="book-icon" src="../static/home/Subtract.png" mode="widthFix" />
                  去订场 -->
                    <image class="location-icon" src="../static/home/导航.png" mode="widthFix" />
                    <text class="distance-text">{{ court.distance }}km</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      <view v-if="loading" class="loading">加载中...</view>
      <view v-else-if="hasMore" class="load-more" @click="$emit('load-more')">点击加载更多</view>
      <view v-else class="no-more">没有更多了</view>
      <view class="customer-service-section">
        <button open-type="contact" class="customer-service-text">
          联系客服
        </button>
      </view>
    </scroll-view>
    

    <!-- 自定义模态框 -->
    <view v-if="showCustomModal" class="custom-modal-mask" @click="closeModal">
      <view class="custom-modal" @click.stop>
        <view class="modal-header">联系客服</view>
        <view class="modal-content">添加微信：ZHAIHANNENG</view>
        <view class="modal-footer">
          <view class="modal-button customer-service-cancel" @click="closeModal">取消</view>
          <view class="modal-button customer-service-copy" @click="copyWechat">复制微信号</view>
        </view>
      </view>
    </view>
    
    <!-- 地址选择弹窗 -->
    <view v-if="showAddressModal" class="custom-modal-mask" @click="closeAddressModal">
      <view class="custom-modal" @click.stop>
        <view class="modal-header">选择地址</view>
        <view class="modal-content">
          <view class="address-list">
            <view 
              v-for="(address, index) in venueAddresses" 
              :key="index" 
              class="address-item"
              @click="selectAddress(address)"
            >
              <view class="address-location">{{ address.location }}</view>
              <view class="address-detail">{{ address.address }}</view>
              <view class="address-primary" v-if="address.isPrimary">主要地址</view>
            </view>
          </view>
        </view>
        <view class="modal-footer">
          <view class="modal-button cancel-button" @click="closeAddressModal">取消</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { get } from '../common/request.js';
import { getVenueByName, getVenueByDataSource, getVenueCoordinates, getVenueAddress, getVenueAllAddresses } from '../common/venueConfig.js';
import courtTypeConfig from './courtTypeConfig.json';

export default {
  name: 'VenueListNew',
  props: {
    venues: {
      type: Array,
      default: () => []
    },
    loading: {
      type: Boolean,
      default: false
    },
    hasMore: {
      type: Boolean,
      default: true
    },
    selectedDate: {
      type: String,
      default: ''
    },
    selectedTimeSlots: {
      type: Array,
      default: () => []
    },
    selectedCourtType: {
      type: String,
      default: '不限'
    },
    showStandardCourtsOnly: {
      type: Boolean,
      default: true
    },
    isVenueListExpanded: {
      type: Boolean,
      default: false
    },
    showExpandedVenueList: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      showCustomModal: false,
      showAddressModal: false,
      currentVenue: null,
      venueAddresses: [],
      userLocation: null,
      courtTypeConfig: courtTypeConfig,

    }
  },
  
  computed: {
    groupedVenues() {
      // 首先过滤标准场
      let filteredVenues = this.venues;
      
      if (this.showStandardCourtsOnly) {
        filteredVenues = this.venues.filter(venue => this.isStandardCourt(venue));
      }
      
      // 按球馆名称分组
      const groups = {};
      filteredVenues.forEach(venue => {
        const dataSource = venue.dataSource;
        if (!groups[dataSource]) {
          groups[dataSource] = {
            name: this.getVenueName(dataSource),
            logo: this.getVenueLogo(dataSource),
            address: this.getVenueAddressByDataSource(dataSource),
            distance: venue.distance || '0',
            dataSource: dataSource,
            venues: [],
            courts: []
          };
        } else {
          // 如果已存在该球馆组，比较距离并保留最近的
          const currentDistance = parseFloat(groups[dataSource].distance);
          const newDistance = parseFloat(venue.distance || '0');
          if (newDistance < currentDistance) {
            groups[dataSource].distance = venue.distance || '0';
          }
        }
        
        groups[dataSource].venues.push(venue);
        
        // 获取场地的空闲时间
        const availableTimeSlots = this.getAvailableTimeSlots(venue);
        
        // 获取场地类型
        const courtType = this.getCourtType(venue);
        
        groups[dataSource].courts.push({
          name: venue.name,
          availableTimeSlots: availableTimeSlots,
          courtType: courtType,
          venue: venue,
          distance: venue.distance || '0'
        });
      });
      
      // 按距离排序球馆组
      return Object.values(groups).sort((a, b) => {
        const distanceA = parseFloat(a.distance);
        const distanceB = parseFloat(b.distance);
        return distanceA - distanceB;
      });
    }
  },
  
  mounted() {
    this.getUserLocation();
  },
  
  watch: {
    venues: {
      handler(newVenues) {
        // 当venues加载完成且有用户位置时计算距离
        if (this.userLocation && newVenues && newVenues.length > 0) {
          this.calculateDistances();
        }
      },
      deep: true,
      immediate: true
    }
  },
  
  methods: {
    // 获取球馆显示名称
    getVenueName(dataSource) {
      // 从venueConfig.json获取球馆的正确名称
      const venueInfo = getVenueByDataSource(dataSource);
      if (venueInfo && venueInfo.name) {
        return venueInfo.name;
      }
      
      // 如果在配置中找不到，则返回dataSource本身
      return dataSource;
    },
    
    // 获取球馆logo（第一个字）
    getVenueLogo(dataSource) {
      const name = this.getVenueName(dataSource);
      return name.charAt(0);
    },
    
    // 获取球馆地址
    getVenueAddressByDataSource(dataSource) {
      const venueInfo = getVenueByDataSource(dataSource);
      if (venueInfo && venueInfo.id) {
        return getVenueAddress(venueInfo.id);
      }
      return '地址未知';
    },
    
    // 提取时间槽的价格（支持不同的价格字段）
    getSlotPrice(slot) {
      // 优先使用 realCost，然后是 cost，最后是 price
      if (slot.realCost !== undefined && slot.realCost !== null) {
        return parseFloat(slot.realCost);
      }
      if (slot.cost !== undefined && slot.cost !== null) {
        return parseFloat(slot.cost);
      }
      if (slot.price !== undefined && slot.price !== null) {
        return parseFloat(slot.price);
      }
      return 0;
    },
    
    // 获取价格信息
    getPrice(timeSlots) {
      if (!timeSlots || timeSlots.length === 0) {
        return '暂无价格';
      }
      
      // 辅助函数：计算时间槽的持续时间（分钟）
      const getSlotDurationMinutes = (slot) => {
        try {
          // 优先使用startTime和endTime
          if (slot.startTime && slot.endTime) {
            const startTime = slot.startTime.toString().trim();
            const endTime = slot.endTime.toString().trim();
            
            // 验证时间格式
            if (!startTime.includes(':') || !endTime.includes(':')) {
              return 60; // 默认1小时
            }
            
            const [startHour, startMin] = startTime.split(':').map(Number);
            const [endHour, endMin] = endTime.split(':').map(Number);
            
            // 验证时间数值的有效性
            if (isNaN(startHour) || isNaN(startMin) || isNaN(endHour) || isNaN(endMin)) {
              return 60; // 默认1小时
            }
            
            // 验证时间范围的合理性
            if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 ||
                startMin < 0 || startMin > 59 || endMin < 0 || endMin > 59) {
              return 60; // 默认1小时
            }
            
            const startTotalMinutes = startHour * 60 + startMin;
            const endTotalMinutes = endHour * 60 + endMin;
            
            // 处理跨天的情况
            let duration = endTotalMinutes - startTotalMinutes;
            if (duration <= 0) {
              duration += 24 * 60; // 加上一天的分钟数
            }
            
            return duration;
          }
          
          // 如果没有startTime/endTime，则使用slot.time
          if (!slot.time || typeof slot.time !== 'string') {
            return 60; // 默认1小时
          }
          
          let timeString = slot.time.trim();
          
          // 检查时间格式，如果不包含'-'，说明是单个时间点
          if (!timeString.includes('-')) {
            // 如果是单个时间点（如"08:00"），自动转换为时间范围（如"08:00-09:00"）
            if (timeString.includes(':')) {
              const [hour, minute] = timeString.split(':').map(Number);
              
              // 验证时间数值的有效性
              if (isNaN(hour) || isNaN(minute) || hour < 0 || hour > 23 || minute < 0 || minute > 59) {
                return 60; // 默认1小时
              }
              
              // 自动转换为1小时时间范围
              const nextHour = (hour + 1) % 24;
              const startTime = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
              const endTime = `${nextHour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
              timeString = `${startTime}-${endTime}`;
              
            } else {
              return 60; // 默认1小时
            }
          }
          
          const [startTime, endTime] = timeString.split('-');
          
          // 检查分割后的时间部分是否有效
          if (!startTime || !endTime) {
            return 60; // 默认1小时
          }
          
          // 检查时间格式是否包含冒号
          if (!startTime.includes(':') || !endTime.includes(':')) {
            return 60; // 默认1小时
          }
          
          const [startHour, startMin] = startTime.split(':').map(Number);
          const [endHour, endMin] = endTime.split(':').map(Number);
          
          // 验证时间数值的有效性
          if (isNaN(startHour) || isNaN(startMin) || isNaN(endHour) || isNaN(endMin)) {
            return 60; // 默认1小时
          }
          
          // 验证时间范围的合理性
          if (startHour < 0 || startHour > 23 || endHour < 0 || endHour > 23 ||
              startMin < 0 || startMin > 59 || endMin < 0 || endMin > 59) {
            return 60; // 默认1小时
          }
          
          const startTotalMinutes = startHour * 60 + startMin;
          const endTotalMinutes = endHour * 60 + endMin;
          
          // 处理跨天的情况
          let duration = endTotalMinutes - startTotalMinutes;
          if (duration <= 0) {
            duration += 24 * 60; // 加上一天的分钟数
          }
          
          return duration;
        } catch (error) {
          console.error('Error calculating slot duration:', error, slot);
          return 60; // 默认1小时
        }
      };
      
      // 辅助函数：将价格转换为小时价格（智能处理）
      const convertToHourlyPrice = (price, durationMinutes) => {
        // 如果时长是标准的30分钟或60分钟，直接按比例转换
        if (durationMinutes === 30) {
          return price * 2; // 半小时价格乘以2
        } else if (durationMinutes === 60) {
          return price; // 一小时价格不变
        } else if (durationMinutes === 90) {
          return Math.round(price * 2 / 3); // 1.5小时价格转换为小时价格
        } else if (durationMinutes === 120) {
          return Math.round(price / 2); // 2小时价格转换为小时价格
        } else {
          // 对于其他不规则时长，使用更保守的处理方式
          // 如果时长接近30分钟（25-35分钟），按半小时处理
          if (durationMinutes >= 25 && durationMinutes <= 35) {
            return price * 2;
          }
          // 如果时长接近60分钟（55-65分钟），按一小时处理
          else if (durationMinutes >= 55 && durationMinutes <= 65) {
            return price;
          }
          // 如果时长接近90分钟（85-95分钟），按1.5小时处理
          else if (durationMinutes >= 85 && durationMinutes <= 95) {
            return Math.round(price * 2 / 3);
          }
          // 如果时长接近120分钟（115-125分钟），按2小时处理
          else if (durationMinutes >= 115 && durationMinutes <= 125) {
            return Math.round(price / 2);
          }
          // 对于其他异常时长，返回原价格（避免产生奇怪的数字）
          else {
            return price;
          }
        }
      };
      
      // 如果有选择时间，则提取选择时间范围内的价格
      if (this.selectedTimeSlots && this.selectedTimeSlots.length > 0) {
        const selectedPrices = [];
        
        // 智能时间匹配函数
        const findMatchingSlot = (selectedSlot, timeSlots) => {
          // 1. 首先尝试严格相等匹配
          let matchingSlot = timeSlots.find(slot => slot.time === selectedSlot);
          if (matchingSlot) {
            return matchingSlot;
          }
          
          // 1.5. 尝试匹配startTime/endTime格式的时间槽
          for (const slot of timeSlots) {
            if (slot.startTime && slot.endTime) {
              const startTime = slot.startTime.toString().trim();
              const endTime = slot.endTime.toString().trim();
              const slotTimeRange = `${startTime}-${endTime}`;
              
              if (slotTimeRange === selectedSlot) {
                console.log(`StartTime/EndTime格式匹配: ${startTime}-${endTime} === ${selectedSlot}`);
                return slot;
              }
            }
          }
          
          // 2. 如果没有找到，尝试处理单个时间点的情况
          const singleTimeSlots = timeSlots.filter(slot => slot.time && !slot.time.includes('-'));
          for (const slot of singleTimeSlots) {
            // 将单个时间点转换为时间范围进行比较
            const singleTime = slot.time;
            if (singleTime.includes(':')) {
              const [hour, minute] = singleTime.split(':').map(Number);
              if (!isNaN(hour) && !isNaN(minute)) {
                const nextHour = (hour + 1) % 24;
                const convertedTimeRange = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}-${nextHour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
                if (convertedTimeRange === selectedSlot) {
                  return slot;
                }
              }
            }
          }
          
          // 3. 尝试时间重叠匹配
          if (selectedSlot.includes('-')) {
            const [selectedStart, selectedEnd] = selectedSlot.split('-');
            const selectedStartMinutes = timeToMinutes(selectedStart);
            const selectedEndMinutes = timeToMinutes(selectedEnd);
            
            for (const slot of timeSlots) {
              let slotStart, slotEnd;
              
              // 优先使用startTime/endTime
              if (slot.startTime && slot.endTime) {
                slotStart = slot.startTime.toString().trim();
                slotEnd = slot.endTime.toString().trim();
              } else if (slot.time && slot.time.includes('-')) {
                [slotStart, slotEnd] = slot.time.split('-');
              } else {
                continue; // 跳过无法处理的时间格式
              }
              
              const slotStartMinutes = timeToMinutes(slotStart);
              const slotEndMinutes = timeToMinutes(slotEnd);
              
              // 检查时间是否有重叠
              if (selectedStartMinutes < slotEndMinutes && selectedEndMinutes > slotStartMinutes) {
                const slotTimeDisplay = slot.startTime && slot.endTime ? 
                  `${slotStart}-${slotEnd}` : slot.time;
                return slot;
              }
            }
          }
          
          return null;
        };
        
        // 时间转换为分钟的辅助函数
        const timeToMinutes = (timeStr) => {
          const [hours, minutes] = timeStr.split(':').map(Number);
          return hours * 60 + minutes;
        };
        
        this.selectedTimeSlots.forEach(selectedSlot => {
          
          const matchingSlot = findMatchingSlot(selectedSlot, timeSlots);
          
          if (matchingSlot) {
            const price = this.getSlotPrice(matchingSlot);
            // 只有价格大于0的时间槽才参与计算
            if (price > 0) {
              const duration = getSlotDurationMinutes(matchingSlot);
              const hourlyPrice = convertToHourlyPrice(price, duration);
              selectedPrices.push(hourlyPrice);
            } else {
            }
          } else {
            console.log(`未找到匹配的时间槽或价格为空: ${selectedSlot}`);
          }
        });
        
        if (selectedPrices.length === 0) {
          return '暂无价格';
        }
        
        // 如果所有选择的时间槽价格相同
        const uniquePrices = [...new Set(selectedPrices)];
        if (uniquePrices.length === 1) {
          return `¥${uniquePrices[0]}/小时`;
        } else {
          // 如果价格不同，显示价格范围
          const minPrice = Math.min(...selectedPrices);
          const maxPrice = Math.max(...selectedPrices);
          return `¥${minPrice}-${maxPrice}/小时`;
        }
      } else {
        // 如果没有选择时间，总结所有时间槽的价格
        const allPrices = timeSlots
          .filter(slot => {
            const price = this.getSlotPrice(slot);
            return !isNaN(price) && price > 0;
          })
          .map(slot => {
            const price = this.getSlotPrice(slot);
            const duration = getSlotDurationMinutes(slot);
            return convertToHourlyPrice(price, duration);
          });
        
        if (allPrices.length === 0) {
          return '暂无价格';
        }
        
        // 获取价格的唯一值
        const uniquePrices = [...new Set(allPrices)].sort((a, b) => a - b);
        
        if (uniquePrices.length === 1) {
          // 所有时间槽价格相同
          return `¥${uniquePrices[0]}/小时`;
        } else {
          // 价格不同，显示价格范围
          const minPrice = uniquePrices[0];
          const maxPrice = uniquePrices[uniquePrices.length - 1];
          return `¥${minPrice}-${maxPrice}/小时`;
        }
      }
    },
    
    // 获取场地的空闲时间
    getAvailableTimeSlots(venue) {
      if (!venue.timeSlots || venue.timeSlots.length === 0) {
        return [];
      }
      
      // 规范化时间格式的辅助函数
      const normalizeTimeSlot = (timeSlot) => {
        if (!timeSlot || !timeSlot.includes('-')) return timeSlot;
        
        const [startTime, endTime] = timeSlot.split('-');
        
        const normalizeTime = (time) => {
          const [hours, minutes] = time.split(':').map(Number);
          let normalizedMinutes = minutes;
          let normalizedHours = hours;
          
          // 规范化分钟数：0-14分钟显示为00，15-44分钟显示为30，45-59分钟显示为下一小时的00
          if (normalizedMinutes >= 45) {
            normalizedHours = (normalizedHours + 1) % 24;
            normalizedMinutes = 0;
          } else if (normalizedMinutes >= 15) {
            normalizedMinutes = 30;
          } else {
            normalizedMinutes = 0;
          }
          
          return `${normalizedHours.toString().padStart(2, '0')}:${normalizedMinutes.toString().padStart(2, '0')}`;
        };
        
        return `${normalizeTime(startTime)}-${normalizeTime(endTime)}`;
      };
      
      // 如果有选择时间，则只显示选择的时间中空闲的
      if (this.selectedTimeSlots && this.selectedTimeSlots.length > 0) {
        const availableSlots = [];
        
        this.selectedTimeSlots.forEach(selectedSlot => {
          const matchingSlot = venue.timeSlots.find(slot => {
            // 检查价格和空闲状态
            const price = this.getSlotPrice(slot);
            if (!slot.isFree || price <= 0) {
              return false;
            }
            
            // 优先匹配slot.time
            if (slot.time === selectedSlot) {
              return true;
            }
            
            // 如果没有slot.time，尝试匹配startTime/endTime格式
            if (slot.startTime && slot.endTime) {
              const startTime = slot.startTime.toString().trim();
              const endTime = slot.endTime.toString().trim();
              const slotTimeRange = `${startTime}-${endTime}`;
              return slotTimeRange === selectedSlot;
            }
            
            return false;
          });
          
          if (matchingSlot) {
            availableSlots.push(normalizeTimeSlot(selectedSlot));
          }
        });
        
        return availableSlots;
      } else {
        // 如果没有选择时间，显示当天所有空闲时间
        return venue.timeSlots
          .filter(slot => {
            const price = this.getSlotPrice(slot);
            return slot.isFree && price > 0;
          })
          .map(slot => {
            // 优先使用slot.time，如果没有则使用startTime-endTime格式
            if (slot.time) {
              return normalizeTimeSlot(slot.time);
            } else if (slot.startTime && slot.endTime) {
              const startTime = slot.startTime.toString().trim();
              const endTime = slot.endTime.toString().trim();
              const timeRange = `${startTime}-${endTime}`;
              return normalizeTimeSlot(timeRange);
            }
            return null;
          })
          .filter(timeSlot => timeSlot !== null) // 过滤掉无效的时间槽
          .slice(0, 8); // 最多显示8个时间段
      }
    },
    
    // 获取场地类型
    getCourtType(venue) {
      // 如果选择了特定球场类型，则显示该类型
      if (this.selectedCourtType && this.selectedCourtType !== '不限') {
        return this.selectedCourtType;
      }
      
      // 否则根据配置文件判断场地类型
      const venueName = venue.name;
      const dataSource = venue.dataSource;
      
      // 遍历球场类型配置
      for (const [courtType, venues] of Object.entries(this.courtTypeConfig)) {
        if (courtType === '不限') continue;
        
        const venueConfig = venues[dataSource];
        if (!venueConfig) continue;
        
        // 检查是否匹配
        if (Array.isArray(venueConfig)) {
          if (venueConfig.some(configName => venueName.includes(configName))) {
            return courtType;
          }
        } else {
          // 如果配置了exclude，先检查是否在排除列表中
          if (venueConfig.exclude && venueConfig.exclude.length > 0) {
            const isExcluded = venueConfig.exclude.some(excludeName => venueName.includes(excludeName));
            if (isExcluded) {
              continue; // 被排除，继续检查下一个配置
            }
          }
          
          if (venueConfig.include && venueConfig.include.length > 0) {
            if (venueConfig.include.some(includeName => venueName.includes(includeName))) {
              return courtType;
            }
          } else if (venueConfig.arrayMatch && venueConfig.arrayMatch.length > 0) {
            if (venueConfig.arrayMatch.some(matchWord => venueName.includes(matchWord))) {
              return courtType;
            }
          } else if (venueConfig.includeAll) {
            return courtType;
          }
        }
      }
      
      return '标准场'; // 默认类型
    },
    
    openNavigation(venue) {
      // 从配置文件中获取球馆的详细信息
      const venueConfig = getVenueByDataSource(venue.dataSource);
      
      if (venueConfig) {
        const allAddresses = getVenueAllAddresses(venueConfig.id);
        
        if (allAddresses.length > 1) {
          // 如果有多个地址，检查当前场的名字是否在include数组内
          let targetAddress = null;
          
          for (let address of allAddresses) {
            if (address.include && address.include.includes(venue.name)) {
              targetAddress = address;
              break;
            }
          }
          
          if (targetAddress) {
            // 如果找到匹配的地址，直接导航
            this.navigateToAddress(venueConfig, targetAddress);
          } else {
            // 如果没有找到匹配的地址，显示地址选择弹窗
            this.currentVenue = venueConfig;
            this.venueAddresses = allAddresses;
            this.showAddressModal = true;
          }
        } else {
          // 如果只有一个地址，直接导航
          this.navigateToAddress(venueConfig, allAddresses[0]);
        }
      } else {
        uni.showToast({
          title: '球馆配置信息未找到',
          icon: 'none'
        });
      }
    },
    
    navigateToAddress(venueConfig, address) {
      uni.openLocation({
        latitude: address.latitude,
        longitude: address.longitude,
        name: venueConfig.name,
        address: address.address,
        success: function() {
          console.log('打开导航成功');
        },
        fail: function(err) {
          console.error('打开导航失败', err);
          uni.showToast({
            title: '导航功能暂不可用',
            icon: 'none'
          });
        }
      });
    },
    
    selectAddress(address) {
      this.navigateToAddress(this.currentVenue, address);
      this.showAddressModal = false;
    },
    
    closeAddressModal() {
      this.showAddressModal = false;
      this.currentVenue = null;
      this.venueAddresses = [];
    },
    
    goToDetail(venue) {
      // 跳转到场地详情页
      // uni.navigateTo({
      //   url: `/pages/venue/detail?venueId=${venue.id}`
      // })
    },
    
    toggleVenueDetails(groupIndex) {
      // 获取选中的球馆组信息
      console.log("venueGroup",this.groupedVenues[groupIndex]);
      
      const venueGroup = this.groupedVenues[groupIndex];
      if (venueGroup) {
        // 构建场地列表数据，包含真实的场地名称
        const venueData = {
          name: venueGroup.name,
          address: venueGroup.address,
          dataSource: venueGroup.dataSource,
          courts: venueGroup.venues.map(venue => ({
            name: venue.name,
            courtName: venue.name,
            description: venue.description || '(标准场地)',
            status: venue.status || '空闲',
            timeSlot: venue.timeSlots || '1小时'
          }))
        };
        
        // 跳转到球馆详情页面，传递球馆信息和场地列表
        uni.navigateTo({
          url: `/pages/courtDetail/index?dataSource=${encodeURIComponent(venueGroup.dataSource)}&name=${encodeURIComponent(venueGroup.name)}&address=${encodeURIComponent(venueGroup.address)}&distance=${venueGroup.distance}&allVenueList=${encodeURIComponent(JSON.stringify([venueData]))}`
        });
      }
    },
    
    contactCustomerService() {
      this.showCustomModal = true;
    },
    
    closeModal() {
      this.showCustomModal = false;
    },
    
    copyWechat() {
      // 复制微信号到剪贴板
      uni.setClipboardData({
        data: 'ZHAIHANNENG',
        success: () => {
          uni.showToast({
            title: '微信号已复制',
            icon: 'success',
            duration: 2000
          });
          this.closeModal();
        }
      });
    },
    
    getUserLocation() {
      uni.getLocation({
        type: 'gcj02',
        success: (res) => {
          this.userLocation = {
            latitude: res.latitude,
            longitude: res.longitude
          };
          console.log('获取用户位置成功:', this.userLocation);
          
          // 获取位置成功后，如果venues已加载则计算距离
          if (this.venues && this.venues.length > 0) {
            this.calculateDistances();
          }
        },
        fail: (err) => {
          console.error('获取位置失败1', err);
          // uni.showToast({
          //   title: '获取位置失败1'+err,
          //   icon: 'none'
          // });
          this.userLocation = {
            latitude: 23.025036,
            longitude: 113.713612
          };
          if (this.venues && this.venues.length > 0) {
            this.calculateDistances();
          }
        },
        
      });
    },
    
    calculateDistances() {
      // 确保用户位置和venues都已加载
      if (!this.userLocation || !this.venues || this.venues.length === 0) {
        console.log('calculateDistances: 数据未准备好', {
          userLocation: !!this.userLocation,
          venues: this.venues ? this.venues.length : 0
        });
        return;
      }
      
      
      const venuesWithDistance = this.venues.map(venue => {
        const venueConfig = getVenueByDataSource(venue.dataSource);
        if (venueConfig) {
          // 根据场馆名称匹配include数组来选择正确的地址
          let targetAddress = null;
          // 遍历所有地址，查找include数组包含当前场馆名称的地址
          for (let address of venueConfig.addresses) {
            if (address.include && address.include.includes(venue.name)) {
              targetAddress = address;
              targetAddress['name'] = venue.name
              break;
            }
          }
          
          
          // 如果没有找到匹配的地址，则使用主要地址或第一个地址
          if (!targetAddress) {
            targetAddress = venueConfig.addresses.find(addr => addr.isPrimary) || venueConfig.addresses[0];
          }
          
          const distance = this.getDistance(
            this.userLocation.latitude,
            this.userLocation.longitude,
            targetAddress.latitude,
            targetAddress.longitude
          );
          return {
            ...venue,
            distance: distance.toFixed(1) 
          };
        }
        return venue;
      });
      
      // 根据距离从小到大排序
      venuesWithDistance.sort((a, b) => {
        const distanceA = parseFloat(a.distance);
        const distanceB = parseFloat(b.distance);
        return distanceA - distanceB;
      });
      
      // 更新venues数组
      this.$emit('update:venues', venuesWithDistance);
    },
    
    getDistance(lat1, lon1, lat2, lon2) {
      // 注意：参数顺序是 (纬度, 经度)
      
      // 将GCJ-02坐标转换为WGS-84坐标（球馆配置中的坐标是WGS-84）
      const wgs2 = this.gcj02ToWgs84(lat1, lon1);
      
      const R = 6371; // 地球半径，单位千米
      const dLat = this.deg2rad(lat2 - wgs2.lat);
      const dLon = this.deg2rad(lon2 - wgs2.lng);
      const a = 
        Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(this.deg2rad(wgs2.lat)) * Math.cos(this.deg2rad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2);
      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
      const distance = R * c; // 单位千米
      
      return distance;
    },
    
    // GCJ-02 转换为 WGS-84
    gcj02ToWgs84(lat, lng) {
      if (this.outOfChina(lat, lng)) {
        return { lat, lng };
      }
      
      let dLat = this.transformLat(lng - 105.0, lat - 35.0);
      let dLng = this.transformLng(lng - 105.0, lat - 35.0);
      const radLat = lat / 180.0 * Math.PI;
      let magic = Math.sin(radLat);
      magic = 1 - 0.00669342162296594323 * magic * magic;
      const sqrtMagic = Math.sqrt(magic);
      dLat = (dLat * 180.0) / ((6378245.0 * (1 - 0.00669342162296594323)) / (magic * sqrtMagic) * Math.PI);
      dLng = (dLng * 180.0) / (6378245.0 / sqrtMagic * Math.cos(radLat) * Math.PI);
      
      return {
        lat: lat - dLat,
        lng: lng - dLng
      };
    },
    
    // 判断是否在中国境内
    outOfChina(lat, lng) {
      return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55);
    },
    
    transformLat(x, y) {
      let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
      ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(y * Math.PI) + 40.0 * Math.sin(y / 3.0 * Math.PI)) * 2.0 / 3.0;
      ret += (160.0 * Math.sin(y / 12.0 * Math.PI) + 320 * Math.sin(y * Math.PI / 30.0)) * 2.0 / 3.0;
      return ret;
    },
    
    transformLng(x, y) {
      let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
      ret += (20.0 * Math.sin(6.0 * x * Math.PI) + 20.0 * Math.sin(2.0 * x * Math.PI)) * 2.0 / 3.0;
      ret += (20.0 * Math.sin(x * Math.PI) + 40.0 * Math.sin(x / 3.0 * Math.PI)) * 2.0 / 3.0;
      ret += (150.0 * Math.sin(x / 12.0 * Math.PI) + 300.0 * Math.sin(x / 30.0 * Math.PI)) * 2.0 / 3.0;
      return ret;
    },
    
    deg2rad(deg) {
      return deg * (Math.PI/180);
    },
    
    isStandardCourt(venue) {
      // 判断是否为标准场
      // 获取场地类型
      const courtType = this.getCourtType(venue);
      
      // 如果场地类型是"非标准场"，则不是标准场
      return courtType !== '非标准场';
    },

    goToBooking(venue) {
      console.log('venue',venue);
      
      // 格式化日期函数（去掉年份，格式化为月-日，不添加前导零）
      const formatDateWithoutYear = (dateStr) => {
        const date = new Date(dateStr);
        const month = (date.getMonth() + 1).toString();
        const day = date.getDate().toString();
        return `${month}-${day}`;
      };
      
      // 根据dataSource判断是否跳转到其他小程序
      if (venue.dataSource === '库卡网球') {
        // 跳转到库卡俱乐部小程序
        uni.navigateToMiniProgram({
          appId: 'wxcd599231d6596bf3',
          path: 'mpxPackages/sport/pages/venue-booking', // 可以指定跳转的页面路径
					extraData: {
						foo: 'bar'
					},
					envVersion: 'release',
          success: (res) => {
            console.log('跳转到库卡俱乐部小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到库卡俱乐部小程序失败', err);
            // uni.showToast({
            //   title: '跳转失败',
            //   icon: 'none'
            // });
          }
        });
      } else if (venue.dataSource === '向阳彩鸿湾') {
        // 跳转到向阳彩鸿湾小程序
        uni.navigateToMiniProgram({
          appId: 'wx080bd287ac7c0a2d',
          path: 'pages/detail/detail?id=403170525',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到向阳彩鸿湾小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到向阳彩鸿湾小程序失败', err);
          }
        });
      } else if (venue.dataSource === '向阳康帝校区') {
        // 跳转到向阳康帝校区小程序
        uni.navigateToMiniProgram({
          appId: 'wx080bd287ac7c0a2d',
          path: 'pages/detail/detail?id=403144937',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到向阳康帝校区小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到向阳康帝校区小程序失败', err);
          }
        });
      } else if (venue.dataSource === '向阳雅园校区') {
        // 跳转到向阳雅园校区小程序
        uni.navigateToMiniProgram({
          appId: 'wx080bd287ac7c0a2d',
          path: 'pages/detail/detail?id=403150429',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到向阳雅园校区小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到向阳雅园校区小程序失败', err);
          }
        });
      } else if (venue.dataSource === '向阳33小镇校区') {
        // 跳转到向阳33小镇校区小程序
        uni.navigateToMiniProgram({
          appId: 'wx080bd287ac7c0a2d',
          path: 'pages/detail/detail?id=403143353',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到向阳33小镇校区小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到向阳33小镇校区小程序失败', err);
          }
        });
      } else if (venue.dataSource === '向阳星河城校区') {
        // 跳转到向阳星河城校区小程序
        uni.navigateToMiniProgram({
          appId: 'wx080bd287ac7c0a2d',
          path: 'pages/detail/detail?id=403102307',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到向阳星河城校区小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到向阳星河城校区小程序失败', err);
          }
        });
      } else if (venue.dataSource === '向阳振兴城校区') {
        // 跳转到向阳振兴城校区小程序
        uni.navigateToMiniProgram({
          appId: 'wx080bd287ac7c0a2d',
          path: 'pages/detail/detail?id=403160622',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到向阳振兴城校区小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到向阳振兴城校区小程序失败', err);
          }
        });
      } else if (venue.dataSource === '拓德网球俱乐部') {
        // 跳转到拓德网球俱乐部小程序
        uni.navigateToMiniProgram({
          appId: 'wx7cb33b5481dbfde4',
          path: 'pages/detail/detail?id=2112235080',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到拓德网球俱乐部小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到拓德网球俱乐部小程序失败', err);
          }
        });
      }else if (venue.dataSource === '爱动金丰网球俱乐部') {
        // 跳转到爱动金丰网球俱乐部小程序
        uni.navigateToMiniProgram({
          appId: 'wxbb9d5b3237778386',
          path: 'mpxPackages/sport/pages/venue-booking',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到爱动金丰网球俱乐部小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到爱动金丰网球俱乐部小程序失败', err);
          }
        });
      } else if (venue.dataSource === '卓乐网球') {
        // 跳转到爱动金丰网球俱乐部小程序
        uni.navigateToMiniProgram({
          appId: 'wx92d22e775454c87f',
          path: 'subPages/education/pages/venue/booking',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到卓乐网球俱乐部小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到卓乐网球俱乐部小程序失败', err);
          }
        });
      } else if (venue.dataSource === '爱力网球') {
        // 跳转到爱力网球俱乐部小程序
        uni.navigateToMiniProgram({
          appId: 'wx852462a7ef513cbf',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到爱力网球俱乐部小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到爱力网球俱乐部小程序失败', err);
          }
        });
      } else if (venue.dataSource === '东城体育公园') {
        // 跳转到东城体育公园小程序
        const formattedDate = formatDateWithoutYear(this.selectedDate || new Date().toISOString().split('T')[0]);
        console.log("formattedDate",formattedDate);
        
        uni.navigateToMiniProgram({
          appId: 'wx8d10f95b126926f3',
          
          // path: `pages/subscribeField/subscribeField?gym_id=1&before_date=5&order_sch_num_limit=5&date=${formattedDate}&site_open_end_time=22:00&site_open_start_time=06:00&type=site&site_bill_unit=60`,
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到东城体育公园小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到东城体育公园小程序失败', err);
          }
        });
      } else if (venue.dataSource === '东莞市体育中心') {
        // 跳转到东莞市体育中心小程序
        const formattedDate = formatDateWithoutYear(this.selectedDate || new Date().toISOString().split('T')[0]);
        uni.navigateToMiniProgram({
          appId: 'wx1580fe42a03dad09',
          // path: `pages/subscribeField/subscribeField?gym_id=5&site_bill_unit=60&type=site&site_open_end_time=22:00&before_date=6&site_open_start_time=06:00&date=${formattedDate}`,
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到东莞市体育中心小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到东莞市体育中心小程序失败', err);
          }
        });

      } else if (venue.dataSource === '3.5+网球（新基）') {
        // 跳转到3.5+网球（新基）小程序
        uni.navigateToMiniProgram({
          appId: 'wxbba37fa369c19fac',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到3.5+网球（新基）小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到3.5+网球（新基）小程序失败', err);
          }
        });
      } else if(venue.dataSource === '3.5+网球（金色华庭店）'){
        uni.navigateToMiniProgram({
          appId: 'wxbba37fa369c19fac',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到3.5+网球（新基）小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到3.5+网球（新基）小程序失败', err);
          }
        });
      } else if (venue.dataSource === '松山湖太鲁阁公园') {
        // 跳转到松山湖太鲁阁公园小程序
        const formattedDate = formatDateWithoutYear(this.selectedDate || new Date().toISOString().split('T')[0]);
        console.log("formattedDate", formattedDate);
        
        uni.navigateToMiniProgram({
          appId: 'wx9b73889b14b32f3d',
          path: `pages/subscribeField/subscribeField?leave_check=0&is_ticket=0&order_sites_max=3&gym_id=42&site_bill_unit=60&site_reserve_before_date=3&is_unique=1&order_sch_num_limit=undefined&name=太鲁阁公园体育场-网球场&date=${formattedDate}&plague_pvt=0&site_open_end_time=22:00&site_open_start_time=07:00&ticket_reserve_before_date=3&type=site&is_site=1`,
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到松山湖太鲁阁公园小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到松山湖太鲁阁公园小程序失败', err);
          }
        });
      } else if (venue.dataSource === '为傲网球（香树店）') {
        // 跳转到为傲网球（香树店）小程序
        uni.navigateToMiniProgram({
          appId: 'wxb220eeda2e7b1a68',
          path: 'main/pages/order/venue?venueTabsType=1&type=1&id=863',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到为傲网球（香树店）小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到为傲网球（香树店）小程序失败', err);
          }
        });
      } else if (venue.dataSource === '3.5+网球（福地）') {
        // 跳转到3.5+网球（福地）小程序
        uni.navigateToMiniProgram({
          appId: 'wx2b9954e1caef716e',
          path: 'booking/pages/space/index?type=1&typeId=463560331927552&shopName=福地室内标准场&shopId=455834640958464',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到3.5+网球（福地）小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到3.5+网球（福地）小程序失败', err);
          }
        });
      } else if (venue.dataSource === '埗击网球') {
        // 跳转到埗击网球小程序
        uni.navigateToMiniProgram({
          appId: 'wxb82a611c68b78f40',
          path: 'mpxPackages/sport/pages/venue-booking',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到埗击网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到埗击网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === '源峰网球') {
        // 跳转到源峰网球小程序
        uni.navigateToMiniProgram({
          appId: 'wx8a322a3fb5d9ea1c',
          path: 'mpxPackages/sport/pages/venue-booking',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转源峰网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转源峰网球小程序失败', err);
            
          }
        });
      } else if (venue.dataSource === '罗杰网球') {
        // 跳转到罗杰网球小程序
        uni.navigateToMiniProgram({
          appId: 'wx36f7f7e8642b69c7',
          path: 'pages/pagesA/place-reserve/index?id=17&schoolId=326',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转罗杰网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转罗杰网球小程序失败', err);
            
          }
        });
      } else if (venue.dataSource === '月击网球（丰泰校区）' 
      || venue.dataSource === '月击网球（电商园校区）'
      || venue.dataSource === '月击网球（虎门大道校区）'
      || venue.dataSource === '月击网球（城市之光校区）') {
        // 跳转到月击网球小程序
        uni.navigateToMiniProgram({
          appId: 'wxdfc7d821850778b9',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转月击网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转月击网球小程序失败', err);
          
          }
        });
      } else if (venue.dataSource === '晟旋网球(执信店)') {
        // 跳转到晟旋网球(执信店)小程序
        uni.navigateToMiniProgram({
          appId: 'wx9a6f2da8b2838848',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到晟旋网球(执信店)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到晟旋网球(执信店)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '晟旋网球(大壮国际店)') {
        // 跳转到晟旋网球(大壮国际店)小程序
        uni.navigateToMiniProgram({
          appId: 'wx9a6f2da8b2838848',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到晟旋网球(大壮国际店)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到晟旋网球(大壮国际店)小程序失败', err);
          }
        });
      } else if (venue.dataSource === 'UPTennis三溪SKY店') {
        // 跳转到UPTennis三溪SKY店小程序
        uni.navigateToMiniProgram({
          appId: 'wx6994fbb71debe1de',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到UPTennis三溪SKY店小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到UPTennis三溪SKY店小程序失败', err);
          }
        });
      } else if (venue.dataSource === '快客网球') {
        // 跳转到快客网球小程序
        uni.navigateToMiniProgram({
          appId: 'wxc9475501ea83ac12',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到快客网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到快客网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(中国大酒店)') {
        // 跳转到金满贯(中国大酒店)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(中国大酒店)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(中国大酒店)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '裕丰围江边网球场') {
        // 跳转到金满贯(中国大酒店)小程序
        uni.navigateToMiniProgram({
          appId: 'wxc7f3f7975f41f64b',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('裕丰围江边网球场小程序成功', res);
          },
          fail: (err) => {
            console.error('裕丰围江边网球场小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(皇冠假日)') {
        // 跳转到金满贯(皇冠假日)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(皇冠假日)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(皇冠假日)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(海珠香格里拉)') {
        // 跳转到金满贯(海珠香格里拉)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(海珠香格里拉)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(海珠香格里拉)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(华工北)') {
        // 跳转到金满贯(华工北)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(华工北)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(华工北)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(华工西)') {
        // 跳转到金满贯(华工西)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(华工西)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(华工西)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(畔江花园)') {
        // 跳转到金满贯(畔江花园)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(畔江花园)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(畔江花园)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(天河城喜来登)') {
        // 跳转到金满贯(天河城喜来登)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(天河城喜来登)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(天河城喜来登)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(华工大学城)') {
        // 跳转到金满贯(华工大学城)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(华工大学城)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(华工大学城)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(威斯汀)') {
        // 跳转到金满贯(威斯汀)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(威斯汀)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(威斯汀)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(白云)') {
        // 跳转到金满贯(白云)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(白云)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(白云)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(珠江新城)') {
        // 跳转到金满贯(珠江新城)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(珠江新城)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(珠江新城)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(琶洲保利世贸)') {
        // 跳转到金满贯(琶洲保利世贸)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(琶洲保利世贸)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(琶洲保利世贸)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(华美麓湖)') {
        // 跳转到金满贯(华美麓湖)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(华美麓湖)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(华美麓湖)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(华美学校)') {
        // 跳转到金满贯(华美学校)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(华美学校)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(华美学校)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '金满贯(旗峰山)') {
        // 跳转到金满贯(旗峰山)小程序
        uni.navigateToMiniProgram({
          appId: 'wx43d54f8c2495bdfa',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到金满贯(旗峰山)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到金满贯(旗峰山)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '花果山网球馆') {
        // 跳转到花果山网球馆小程序
        uni.navigateToMiniProgram({
          appId: 'wxc7f3f7975f41f64b',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到花果山网球馆小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到花果山网球馆小程序失败', err);
          }
        });
      } else if (venue.dataSource === '209网球中心') {
        // 跳转到209网球中心小程序
        uni.navigateToMiniProgram({
          appId: 'wxc7f3f7975f41f64b',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到209网球中心小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到209网球中心小程序失败', err);
          }
        });
      } else if (venue.dataSource === '锦林山庄网球馆') {
        // 跳转到锦林山庄网球馆小程序
        uni.navigateToMiniProgram({
          appId: 'wxc7f3f7975f41f64b',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到锦林山庄网球馆小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到锦林山庄网球馆小程序失败', err);
          }
        });
      } else if (venue.dataSource === '丰泰花园网球场') {
        // 跳转到丰泰花园网球场小程序
        uni.navigateToMiniProgram({
          appId: 'wxc7f3f7975f41f64b',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到丰泰花园网球场小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到丰泰花园网球场小程序失败', err);
          }
        });
      } else if (venue.dataSource === '拓普网球(南国花园)') {
        // 跳转到拓普网球(南国花园)小程序
        uni.navigateToMiniProgram({
          appId: 'wx3c3c93c6646e441e',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到拓普网球(南国花园)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到拓普网球(南国花园)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '拓普网球(万胜围)') {
        // 跳转到拓普网球(万胜围)小程序
        uni.navigateToMiniProgram({
          appId: 'wx3c3c93c6646e441e',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到拓普网球(万胜围)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到拓普网球(万胜围)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '拓普网球(新港东)') {
        // 跳转到拓普网球(新港东)小程序
        uni.navigateToMiniProgram({
          appId: 'wx3c3c93c6646e441e',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到拓普网球(新港东)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到拓普网球(新港东)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '拓普网球(白云湖金铂天地)') {
        // 跳转到拓普网球(白云湖金铂天地)小程序
        uni.navigateToMiniProgram({
          appId: 'wx3c3c93c6646e441e',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到拓普网球(白云湖金铂天地)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到拓普网球(白云湖金铂天地)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '健潮网球') {
        // 跳转到健潮网球小程序
        uni.navigateToMiniProgram({
          appId: 'wxb1554a6b6cc70e73',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到健潮网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到健潮网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === '青芸网球') {
        // 跳转到青芸网球小程序
        uni.navigateToMiniProgram({
          appId: 'wx5ac7d00aa9fd734e',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到青芸网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到青芸网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === '全爱网球(荔湾店)') {
        // 跳转到全爱网球(荔湾店)小程序
        uni.navigateToMiniProgram({
          appId: 'wxa23d17ffa705bd30',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到全爱网球(荔湾店)小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到全爱网球(荔湾店)小程序失败', err);
          }
        });
      } else if (venue.dataSource === '云堡罗伦斯网球') {
        // 跳转到云堡罗伦斯网球小程序
        uni.navigateToMiniProgram({
          appId: 'wxc4892bb6d243bb7a',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到云堡罗伦斯网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到云堡罗伦斯网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === '瀚为网球') {
        // 跳转到瀚为网球小程序
        uni.navigateToMiniProgram({
          appId: 'wx673161f76dbe64fd',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到瀚为网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到瀚为网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === 'Mteam网球(嘉禾广丰)') {
        // 跳转到Mteam网球小程序
        uni.navigateToMiniProgram({
          appId: 'wx255c5fad9593085d',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到Mteam网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到Mteam网球小程序失败', err);
          }
        });
      } else if (venue.dataSource === 'Mteam网球(黄埔)') {
        // 跳转到Mteam网球小程序
        uni.navigateToMiniProgram({
          appId: 'wx255c5fad9593085d',
          path: '',
          envVersion: 'release',
          success: (res) => {
            console.log('跳转到Mteam网球小程序成功', res);
          },
          fail: (err) => {
            console.error('跳转到Mteam网球小程序失败', err);
          }
        });
      }
    }
  }
}
</script>

<style scoped>
/* 添加自定义字体 */
@font-face {
  font-family: 'AaHouDiHei';
  src: url('https://mp-0c81a8be-aa9a-4fae-8d6c-54b797768401.cdn.bspapp.com/cloudstorage/SmileySans-Oblique-3.otf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

.venue-container {
  /* padding-bottom: 100px; */
}

.venue-list {
  /* padding: 20rpx; */
  height: calc(100vh - 194rpx - 200rpx);
  box-sizing: border-box;
}

.venue-list-expanded {
  height: calc(100vh - 194rpx - 300rpx) !important;
}

/* 推荐场地样式 */
.recommended-venue {
  padding: 0 20rpx;
  width: 100%;
  box-sizing: border-box;
  /* padding: 20rpx; */
  margin-bottom: 30rpx;
  /* background: #fff; */
  border-radius: 24rpx;
  /* box-shadow: 0 8rpx 32rpx 0 rgba(31, 38, 135, 0.15); */
}
.recommended-venue:last-child {
  margin-bottom: 100rpx;
}

.venue-header {
  display: flex;
}

.venue-logo {
  width: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 32rpx;
  height: 76rpx;
  opacity: 1;
  border-radius: 24rpx;
  margin-right: 20rpx;
  font-weight: bold;
  background: linear-gradient(180deg, #D6FF7D 0%, #42CF7F 100%);
}

.venue-info {
  flex: 1;
}

.venue-name {
  font-size: 34rpx;
  color: #333;
  margin-bottom: 8rpx;
  font-weight: bold;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.venue-address {
  font-size: 26rpx;
  color: #999;
  margin-bottom: 20rpx;
  line-height: 1.4;
}

.venue-details {
  background: #F4F5F7;
  border-radius: 24rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.court-item {
  margin-bottom: 20rpx;
}

.court-item:last-child {
  margin-bottom: 0;
}

.court-name {
  color: #333;
  font-size: 30rpx;
  margin-bottom: 10rpx;
  font-weight: 500;
}

.court-info-row {
  display: flex;
  margin-bottom: 15rpx;
  align-items: flex-start;
}

.court-info-row:last-child {
  margin-bottom: 0;
}

.info-label {
  font-size: 26rpx;
  color: #999;
  line-height: 50rpx;
  margin-right: 20rpx;
  min-width: 80rpx;
}

.time-slots {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}

.time-slot {
  width: fit-content;
  font-size: 23rpx;
  line-height: 50rpx;
  padding: 0 15rpx;
  border-radius: 100px;
  background: #fff;
  color: #666;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.no-time-slots {
  font-size: 23rpx;
  line-height: 50rpx;
  color: #999;
}

.court-type {
  font-size: 26rpx;
  line-height: 50rpx;
  padding: 0 20rpx;
  border-radius: 100px;
  background: #fff;
  color: #666;
  /* margin-left: 20rpx; */
}
.court-type-1 {
  font-size: 26rpx;
  line-height: 50rpx;
  /* padding: 0 20rpx; */
  color: #666;
  /* margin-left: 20rpx; */
}
.venue-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: -70rpx;
}

.venue-location {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.location-icon {
  width: 42rpx;
  height: 42rpx;
  margin-right: 10rpx;
}

.distance-text {
  font-size: 24rpx;
  color: #666;
}

.book-button {
  display: flex;
  width: 163rpx;
  height: 56rpx;
  opacity: 1;
  border-radius: 448px;
  background: #c5ffde;
  justify-content: center;
  align-items: center;
  font-size: 26rpx;
  color: #42CF7F;
  cursor: pointer;
}
.book-button-white {
  display: flex;
  /* width: 163rpx; */
  height: 46rpx;
  opacity: 1;
  border-radius: 448px;
  background: #ffffff; 
  justify-content: flex-start;
  align-items: center;
  font-size: 26rpx;
  color: #fff;
  cursor: pointer;
  padding: 0 20rpx 0 10rpx;

}

.book-icon {
  width: 24rpx;
  height: 24rpx;
  margin-right: 10rpx;
}

.loading, .load-more, .no-more {
  text-align: center;
  padding: 20rpx;
  font-size: 28rpx;
  margin: 20rpx 0;
  transition: all 0.3s ease;
}

.load-more {
  color: #007AFF;
  cursor: pointer;
}

.load-more:hover {
  background: rgba(0, 122, 255, 0.15);
  transform: translateY(-2rpx);
  box-shadow: 0 12rpx 40rpx 0 rgba(0, 122, 255, 0.2);
}

.load-more:active {
  transform: scale(0.98);
}

.no-data {
  text-align: center;
  padding: 40rpx;
  font-size: 28rpx;
  color: #999;
  background: rgba(255, 255, 255, 0.25);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  border-radius: 20rpx;
  border: 1px solid rgba(255, 255, 255, 0.18);
  box-shadow: 0 8rpx 32rpx 0 rgba(31, 38, 135, 0.15);
  margin: 20rpx 0;
}

.customer-service-section {
  padding: 20rpx;
  text-align: center;
  margin-top: 30rpx;
}

.customer-service-text {
  color: #fff;
  font-size: 28rpx;
  cursor: pointer;
  padding: 16rpx 30rpx;
  display: inline-block;
  transition: all 0.3s ease;
  background: rgba(66, 207, 127, 1);
  backdrop-filter: blur(15px);
  -webkit-backdrop-filter: blur(15px);
  border-radius: 300rpx;
  position: relative;
  overflow: hidden;
  font-weight: 500;
  text-align: center;
  /* 去除button默认样式 */
  margin: 0;
  outline: none;
  line-height: 1.4;
  white-space: nowrap;
  -webkit-tap-highlight-color: transparent;
}

.customer-service-text::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s ease;
}

.customer-service-text:hover {
  color: #fff;
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 20rpx 0 rgba(0, 122, 255, 0.4);
  background: rgba(0, 122, 255, 0.9);
}

.customer-service-text:hover::before {
  left: 100%;
}

.customer-service-text:active {
  background: rgba(0, 86, 179, 0.9);
  transform: scale(0.98);
  box-shadow: 0 4rpx 16rpx 0 rgba(0, 122, 255, 0.3);
}

/* 自定义模态框样式 */
.custom-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

.custom-modal {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(20px);
  -webkit-backdrop-filter: blur(20px);
  border-radius: 20rpx;
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 8rpx 32rpx 0 rgba(31, 38, 135, 0.25);
  width: 80%;
  max-width: 600rpx;
  overflow: hidden;
  animation: modalSlideIn 0.3s ease-out;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(50rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  font-size: 32rpx;
  font-weight: bold;
  text-align: center;
  padding: 30rpx 20rpx 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  display: flex;
  justify-content: space-between;
}

.modal-content {
  font-size: 28rpx;
  text-align: center;
  padding: 40rpx 20rpx;
  color: #333;
  line-height: 1.5;
}

.modal-footer {
  display: flex;
  border-top: 1rpx solid #f0f0f0;
}
.section-title-right {
  display: flex;
  align-items: center;
}

.section-more-text {
  color: #999;
  margin-right: 10rpx;
  font-size: 28rpx;
  font-weight: normal !important;
}

.section-more-arrow {
  width: 24rpx;
  height: 24rpx;
}
.modal-button {
  flex: 1;
  text-align: center;
  padding: 25rpx 0;
  font-size: 30rpx;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

/* 联系客服弹窗按钮样式 */
.customer-service-cancel {
  background-color: rgba(245, 245, 245, 0.8);
  backdrop-filter: blur(10px);
  color: #666;
  border-radius: 200rpx;
  font-size: 32rpx;
  border: 1rpx solid rgba(200, 200, 200, 0.5);
  box-shadow: 0 2rpx 8rpx 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  font-weight: 500;
  flex: 1;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  margin-right: 15rpx;
}

.customer-service-cancel:active {
  background-color: rgba(245, 245, 245, 0.9);
  color: #333;
  box-shadow: 0 1rpx 4rpx 0 rgba(0, 0, 0, 0.15);
}

.customer-service-copy {
  background-color: rgba(0, 122, 255, 0.8);
  backdrop-filter: blur(10px);
  color: #fff;
  border-radius: 200rpx;
  font-size: 32rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.3);
  box-shadow: 0 4rpx 16rpx 0 rgba(0, 122, 255, 0.3);
  transition: all 0.3s ease;
  font-weight: 500;
  flex: 1;
  height: 70rpx;
  line-height: 70rpx; 
  text-align: center;
}

.customer-service-copy:active {
  background-color: rgba(0, 86, 179, 0.9);
  backdrop-filter: blur(15px);
  box-shadow: 0 6rpx 20rpx 0 rgba(0, 122, 255, 0.4);
}

/* 地址选择弹窗样式 */
.address-list {
  max-height: 400rpx;
  overflow-y: auto;
}

.address-item {
  padding: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.2s ease;
  position: relative;
}

.address-item:last-child {
  border-bottom: none;
}

.address-item:hover {
  background-color: #f8f9fa;
}

.address-item:active {
  background-color: #e9ecef;
}

.address-location {
  font-size: 28rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
}

.address-detail {
  font-size: 24rpx;
  color: #666;
  line-height: 1.4;
  margin-bottom: 8rpx;
}

.address-primary {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  background-color: #52c41a;
  color: white;
  font-size: 20rpx;
  padding: 4rpx 12rpx;
  border-radius: 12rpx;
  font-weight: 500;
}
</style>